import { createRouter, createWebHistory, Router } from 'vue-router';
import routes from './routes';
import store from '@/store';
import { useUserStore } from '@/store/modules/user';
import { userApi } from '@/api/index';
import { getLang, setLang } from '@/i18n';

const router: Router = createRouter({
  history: createWebHistory('/manage/'),
  routes: routes,
});

const userStore = useUserStore(store);

const toLogin = (_to, _from, next) => {
  next({
    path: '/user/login',
    query: {
      t: new Date().getTime(),
    },
  });
};

const getUserInfo = async (_to, _from, next) => {
  try {
    const res = await userApi({});
    if (res['data'] && res['data']['email']) {
      sessionStorage.setItem('userInfo', JSON.stringify(res['data']));
      userStore.setUserInfo(res['data']);
    } else {
      sessionStorage.removeItem('token');
      sessionStorage.removeItem('userInfo');
      next && toLogin(_to, _from, next);
    }
  } catch (err) {
    next && toLogin(_to, _from, next);
  }
};

const setTitle = (route) => {
  let title = 'IPXProxy';
  if (typeof route.meta.title == 'string') {
    title = route.meta.title;
  } else {
    title = route.meta.title[getLang()];
  }
  document.title = 'IPXProxy -' + title;
};

const setChannel = (route) => {
  const query = route.query || {};
  for (const i in query) {
    if (i == 'hz' || i == 'yl' || i == 'qd') {
      sessionStorage.setItem('channel_key', i);
      sessionStorage.setItem('channel_value', query[i]);
    }
  }
};

const ignorePaths = ['/user/login', '/user/register', '/error'];

router.beforeEach(async (_to, _from, next) => {
  const token = (_to.query.token || sessionStorage.getItem('token')) as string;
  const lang = (_to.query.lang || sessionStorage.getItem('lang')) as string;

  if (lang == 'en') {
    setLang('en');
  } else if (lang == 'zh-cn') {
    setLang('zh-cn');
  } else if (lang == 'zh') {
    setLang('zh');
  }

  setTitle(_to); // 设置网页标题
  setChannel(_to); // 设置渠道来源

  if (ignorePaths.includes(_to.path)) {
    next();
  } else {
    if (token) {
      next();
      // await getUserInfo(_to, _from, next);
    } else {
      toLogin(_to, _from, next);
    }
  }
});

router.afterEach(async (_to, _from) => {
  if (!ignorePaths.includes(_to.path)) {
    await getUserInfo(_to, _from, null);
  }
});

export default router;
